import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

import '../../core/app_initializer.dart';

class PrintLogInterceptor extends Interceptor {
  final Logger logger = AppInitializer.logger;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    logger.i("REQUEST ${options.method} ${options.uri}");

    _printHeaders(options.headers);

    if (options.queryParameters.isNotEmpty) {
      logger.i("Query Parameters:");
      options.queryParameters.forEach((key, value) {
        logger.i("  ↪ $key: $value");
      });
    }

    if (options.data != null) {
      logger.i("Request Body:");
      logger.i("  ↪ ${options.data}");
    }

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    logger.i("RESPONSE ${response.statusCode} ${response.realUri}");

    _printResponseHeaders(response.headers);

    if (response.data != null) {
      logger.i("Response Data:");
      logger.i("  ↪ ${response.data}");
    }

    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    logger.e("ERROR ${err.response?.statusCode} ${err.requestOptions.uri}");

    if (err.message!.isNotEmpty) {
      logger.e("Message: ${err.message}");
    }

    if (err.response?.data != null) {
      logger.e("Error Data:");
      logger.e("  ↪ ${err.response?.data}");
    }

    super.onError(err, handler);
  }

  void _printHeaders(Map<String, dynamic> headers) {
    if (headers.isEmpty) {
      logger.i("Headers: <empty>");
      return;
    }
    logger.i("Request Headers:");
    headers.forEach((key, value) {
      logger.i("  ↪ $key: $value");
    });
  }

  void _printResponseHeaders(Headers headers) {
    if (headers.isEmpty) {
      logger.i("Response Headers: <empty>");
      return;
    }
    logger.i("Response Headers:");
    headers.forEach((key, values) {
      logger.i("  ↪ $key: ${values.join(', ')}");
    });
  }
}

